package nio.file;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * FileContentFindDemo
 *
 * @author chenxin
 * @date 2022/05/16 17:14
 **/
public class FileContentFindDemo {

    public static void main(String[] args) throws IOException {

        AtomicInteger fileCount = new AtomicInteger();
        AtomicInteger dirCount = new AtomicInteger();
        AtomicInteger jarCount = new AtomicInteger();

        // 文件遍历
        Files.walkFileTree(Paths.get("D:\\jdk1.8.0_172"), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                // 进入文件夹之前的操作
                System.out.println("=============> " + dir);
                dirCount.incrementAndGet();
                return super.preVisitDirectory(dir, attrs);
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                // 遍历文件时
                System.out.println(file);
                fileCount.incrementAndGet();

                if (file.toString().endsWith(".jar")) {
                    jarCount.incrementAndGet();
                }

                return super.visitFile(file, attrs);
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                // 遍历文件失败时
                return super.visitFileFailed(file, exc);
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                // 从文件夹出来后
                return super.postVisitDirectory(dir, exc);
            }
        });

        System.out.println("文件数量：" + fileCount);
        System.out.println("文件夹数量：" + dirCount);
        System.out.println("jar文件数量：" + jarCount);
    }


}